
class GoDamh extends ComicSource {
    // 注意: 标记为[可选]的字段如果不使用应删除

    // 源名称
    name = "g站漫画"

    // 源的唯一标识
    key = "GoDamh"

    version = "1.0.1"

    minAppVersion = "1.4.0"

    // 更新链接
    url = "https://gitee.com/cmj_xxgg/comic_yuan/blob/master/g%E7%AB%99%E6%BC%AB%E7%94%BB.js"

    /**
     * [可选] 初始化函数
     */
    init() {
        this.baseUrl = "https://godamh.com/";
    }


    // 探索页面列表
    explore = [
        {
            // 页面标题
            // 标题用于标识页面，应保持唯一
            title: "g站",

            /// multiPartPage（多分区页面）或multiPageComicList（多页漫画列表）或mixed（混合类型）
            type: "singlePageWithMultiPart",

            // 分区列表
            load: async (page) => {

                // 1.获取网页内容
                let res = await Network.get("https://godamh.com")

                if (res.status !== 200) {
                    throw `Invalid status code: ${res.status}`
                }

                // 2. 解析文档
                let doc = new HtmlDocument(res.body);

                // 3. 通用解析单元函数
                function parseItem(el) {
                    // 获取id
                    let id = el.querySelector("a").attributes.href.replace('/manga/', '');
                    // 获取封面
                    let imgEl = el.querySelector("img");
                    let cover = imgEl.attributes.src || imgEl.attributes.data-src;
                    // 获取标题
                    let title = el.querySelector("h3").text.trim();
                    return new Comic({ id, title, cover });
                }

                // 4. 获取热门更新
                let dayup = [];
                let dayupList = doc.querySelectorAll("div.cardlist")[0];
                if (dayupList) {
                    let items = dayupList.querySelectorAll("div.pb-2");
                    for (let el of items) {
                        dayup.push(parseItem(el));
                    }
                }

                // 5. 获取人气排行
                let hot = [];
                let hotList = doc.querySelectorAll("div.cardlist")[1];
                if (hotList) {
                    let items = hotList.querySelectorAll("div.pb-2");
                    for (let el of items) {
                        hot.push(parseItem(el));
                    }
                }

                // 6. 获取最新上架
                let newss = [];
                let newssList = doc.querySelectorAll("div.cardlist")[2];
                if (newssList) {
                    let items = newssList.querySelectorAll("div.pb-2");
                    for (let el of items) {
                        newss.push(parseItem(el));
                    }
                }

                                // 7. 清理并返回
                doc.dispose();
                return {
                    "热门更新": dayup,
                    "人气排行": hot,
                    "最新上架": newss
                };
            },
        }
    ]

    // 分类
    category = {
        /// 分类页面标题，用于标识页面，应保持唯一
        title: "GoDamh",
        parts: [
            {
                // 分区标题
                name: "分类",

                // fixed（固定）或random（随机）或dynamic（动态）
                // 如果是random类型，需要提供`randomNumber`字段，表示同时显示的漫画数量
                // 如果是dynamic类型，需要提供`loader`字段，表示加载漫画的函数
                type: "fixed",

                categories: ['复仇', '古风', '奇幻', '逆袭', '异能', '宅向', '穿越', '热血', '纯爱','系统','重生', '冒险', '灵异', '大女主', '剧情', '恋爱', '玄幻', '魔幻', '女神', '科幻', '推理', '猎奇', '治愈', '都市', '异形', '青春', '末日', '悬疑', '修仙', '战斗'],

                itemType: "category",

                // 若提供, 数量需要和`categories`一致, `categoryComics.load`方法将会收到此参数
                categoryParams: ['fuchou', 'gufeng', 'qihuan', 'nixi', 'yineng', 'zhaixiang', 'chuanyue', 'rexue', 'chunai', 'xitong', 'chongsheng', 'maoxian', 'lingyi', 'danvzhu', 'juqing', 'lianai', 'xuanhuan', 'mohuan', 'nushen', 'kehuan', 'tuili', 'lieqi', 'zhiyu', 'dushi', 'yixing', 'qingchun', 'mori', 'xuanyi', 'xiuxian', 'zhandou']
             }
        ],
        // 启用排行榜页面
        enableRankingPage: false,
    }

    /// 分类漫画加载相关
    categoryComics = {
        /**
         * 加载分类漫画
         * @param category {string} - category name
         * @param param {string?} - category param
         * @param options {string[]} - options from optionList
         * @param page {number} - page number
         * @returns {Promise<{comics: Comic[], maxPage: number}>}
         */
        load: async (category, param, options, page) => {

            // 分类网址
            // https://godamh.com/manga-tag/fuchou

            let url = `${this.baseUrl}manga-tag/${param}?page/${page}`;
            // 发起请求
            let res = await Network.get(url);
            if (res.status !== 200) {
                throw `Invalid status code: ${res.status}`;
            }
            // 解析 HTML
            let document = new HtmlDocument(res.body);

            // 获取最大页数
            // 首先找到aria-label="下一頁"的a标签
            let nextPageButton = document.querySelector('a[aria-label="下一頁"]');
            let lastPageElement = 1;

            // 如果找到了该按钮
            if (nextPageButton) {
                // 获取其同级上一个div元素
                let previousDiv = nextPageButton.previousElementSibling;
                
                // 确保上一个元素是div
                if (previousDiv && previousDiv.tagName === 'DIV') {
                    // 在该div中查找最后一个a标签
                    let lastPageLink = previousDiv.querySelector('a:last-child');
                    
                    // 如果找到了最后一个a标签
                    if (lastPageLink) {
                        // 获取其文本内容
                        lastPageElement = parseInt(lastPageLink.textContent.trim());
                    }
                }
            }

            let maxPage = lastPageElement ? parseInt(lastPageElement.text) : 1;

            // 获取漫画列表
            let mangaList = [];
            let rows = document.querySelectorAll("div.pb-2");
            for (let row of rows) {
                    // 获取id
                    let id = row.querySelector("a").attributes.href.replace('/manga/', '');
                    // 获取封面
                    let cover = row.querySelector("img").attributes.src;
                    // 获取标题
                    let title = row.querySelector("h3").text.trim();

                                        // 构建漫画对象
                    let manga = {
                        id: id,
                        title: title,
                        cover: cover, // 默认封面
                        tags: [''],
                        description: ` `
                    };

                    mangaList.push(manga);
            }

            return {
                comics: mangaList,
                maxPage: maxPage
            };
        },
        // // 为分类漫画加载提供选项
        // optionList: [
        //     {
        //         // 单个选项使用`-`分隔值和文本，左侧为值，右侧为文本
        //         options: [
        //             "newToOld-New to Old",
        //             "oldToNew-Old to New"
        //         ],
        //         // [可选] {string[]} - 仅当值不在列表中时显示此选项
        //         notShowWhen: null,
        //         // [可选] {string[]} - 仅当值在列表中时显示此选项
        //         showWhen: null
        //     }
        // ],
        // ranking: { // 排行榜
        //     // For a single option, use `-` to separate the value and text, left for value, right for text
        //     options: [
        //         "day-Day",
        //         "week-Week"
        //     ],
        //     /**
        //      * 加载排行榜漫画
        //      * @param option {string} - option from optionList
        //      * @param page {number} - page number
        //      * @returns {Promise<{comics: Comic[], maxPage: number}>}
        //      */
        //     load: async (option, page) => {
        //         /*
        //         ```
        //         let data = JSON.parse((await Network.get('...')).body)
        //         let maxPage = data.maxPage

        //         function parseComic(comic) {
        //             // ...

        //             return new Comic({
        //                 id: id,
        //                 title: title,
        //                 subTitle: author,
        //                 cover: cover,
        //                 tags: tags,
        //                 description: description
        //             })
        //         }

        //         return {
        //             comics: data.list.map(parseComic),
        //             maxPage: maxPage
        //         }
        //         ```
        //         */
        //     }
        // }
    }

    /// 搜索相关
    search = {
        /**
         * 加载搜索结果
         * @param keyword {string}
         * @param options {string[]} - options from optionList
         * @param page {number}
         * @returns {Promise<{comics: Comic[], maxPage: number}>}
         */
        load: async (keyword, options, page) => {
            // 搜索网址 https://godamh.com/s/%E8%B6%85%E7%BA%A7?page=2
            let url = `${this.baseUrl}s/${keyword}?page=${page}`;

            let res = await Network.get(url);

            if (res.status !== 200) {throw `Invalid status code: ${res.status}`;}

            let document = new HtmlDocument(res.body);
    
            // 获取最大页数
            // 首先找到aria-label="下一頁"的a标签
            let nextPageButton = document.querySelector('a[aria-label="下一頁"]');
            let lastPageElement = 1
            if (nextPageButton) {
                // 获取其同级上一个div元素
                let previousDiv = nextPageButton.previousElementSibling;
                
                // 确保上一个元素是div
                if (previousDiv && previousDiv.tagName === 'DIV') {
                    // 在该div中查找最后一个a标签
                    let lastPageLink = previousDiv.querySelector('a:last-child');
                    
                    // 如果找到了最后一个a标签
                    if (lastPageLink) {
                        // 获取其文本内容
                        lastPageElement = parseInt(lastPageLink.textContent.trim());
                    }
                }
            }

            let maxPage = lastPageElement ? parseInt(lastPageElement.text) : 1;

            // 获取漫画列表
            let mangaList = [];
            let rows = document.querySelectorAll("div.pb-2");
            for (let row of rows) {
                    // 获取id
                    let id = row.querySelector("a").attributes.href.replace('/manga/', '');
                    // 获取封面
                    let cover = row.querySelector("img").attributes.src;
                    // 获取标题
                    let title = row.querySelector("h3").text.trim();

                                        // 构建漫画对象
                    let manga = {
                        id: id,
                        title: title,
                        cover: cover, // 默认封面
                        tags: [' '],
                        description: ` `
                    };

                    mangaList.push(manga);
            }

            return {
                comics: mangaList,
                maxPage: maxPage
            };
        },

        /**
         * 使用下一页令牌加载搜索结果。
         * The field will be ignored if `load` function is implemented.
         * @param keyword {string}
         * @param options {(string)[]} - options from optionList
         * @param next {string | null}
         * @returns {Promise<{comics: Comic[], maxPage: number}>}
         */
        loadNext: async (keyword, options, next) => {
        },

        // 为搜索提供选项
        optionList: [
        ],

        // 启用标签建议
        enableTagsSuggestions: false,
    }

    // 收藏相关
    favorites = {
        // 是否支持多文件夹
        multiFolder: false,
        /**
         * 添加或删除收藏。
         * 抛出`Login expired`表示登录过期，应用将自动重新登录并重新添加/删除收藏
         * @param comicId {string}
         * @param folderId {string}
         * @param isAdding {boolean} - true for add, false for delete
         * @param favoriteId {string?} - [Comic.favoriteId]
         * @returns {Promise<any>} - return any value to indicate success
         */
        addOrDelFavorite: async (comicId, folderId, isAdding, favoriteId) => {
            /*
            ```
            let res = await Network.post('...')
            if (res.status === 401) {
                throw `Login expired`;
            }
            return 'ok'
            ```
            */
        },
        /**
         * 加载收藏文件夹。
         * throw `Login expired` to indicate login expired, App will automatically re-login retry.
         * if comicId is not null, return favorite folders which contains the comic.
         * @param comicId {string?}
         * @returns {Promise<{folders: {[p: string]: string}, favorited: string[]}>} - `folders` is a map of folder id to folder name, `favorited` is a list of folder id which contains the comic
         */
        loadFolders: async (comicId) => {
            /*
            ```
            let data = JSON.parse((await Network.get('...')).body)

            let folders = {}

            data.folders.forEach((f) => {
                folders[f.id] = f.name
            })

            return {
                folders: folders,
                favorited: data.favorited
            }
            ```
            */
        },
        /**
         * 添加文件夹
         * @param name {string}
         * @returns {Promise<any>} - return any value to indicate success
         */
        addFolder: async (name) => {
            /*
            ```
            let res = await Network.post('...')
            if (res.status === 401) {
                throw `Login expired`;
            }
            return 'ok'
            ```
            */
        },
        /**
         * 删除文件夹
         * @param folderId {string}
         * @returns {Promise<void>} - return any value to indicate success
         */
        deleteFolder: async (folderId) => {
            /*
            ```
            let res = await Network.delete('...')
            if (res.status === 401) {
                throw `Login expired`;
            }
            return 'ok'
            ```
            */
        },
        /**
         * 加载文件夹中的漫画
         * throw `Login expired` to indicate login expired, App will automatically re-login retry.
         * @param page {number}
         * @param folder {string?} - folder id, null for non-multi-folder
         * @returns {Promise<{comics: Comic[], maxPage: number}>}
         */
        loadComics: async (page, folder) => {
            /*
            ```
            let data = JSON.parse((await Network.get('...')).body)
            let maxPage = data.maxPage

            function parseComic(comic) {
                // ...

                return new Comic{
                    id: id,
                    title: title,
                    subTitle: author,
                    cover: cover,
                    tags: tags,
                    description: description
                }
            }

            return {
                comics: data.list.map(parseComic),
                maxPage: maxPage
            }
            ```
            */
        },
        /**
         * 使用下一页令牌加载漫画
         * @param next {string | null} - next page token, null for first page
         * @param folder {string}
         * @returns {Promise<{comics: Comic[], next: string?}>}
         */
        loadNext: async (next, folder) => {

        },
        /**
         * 如果漫画源只允许一个漫画在一个文件夹中，设置为true。
         */
        singleFolderForSingleComic: false,
    }

    /// 单部漫画相关
    comic = {
        /**
         * 加载漫画信息
         * @param id {string}
         * @returns {Promise<ComicDetails>}
         */
        loadInfo: async (id) => {
            // 详情网页 https://godamh.com/manga/wuliandianfeng-pikapi
            let url = `${this.baseUrl}manga/${id}`;

            let res = await Network.get(url);

            if (res.status !== 200) {throw `Invalid status code: ${res.status}`;}

            let document = new HtmlDocument(res.body);

            // 漫画标题
            let title = document.querySelector("h1").text.trim();

            // 漫画封面
            let cover = document.querySelector("div.aspect-3-4 > img").attributes.src;

            // 漫画描述
            let description = document.querySelector("p.text-medium").text.trim();

            // 漫画作者
            let author = document.querySelector("div.text-small").text.trim().replace("作者：", "");

            // 更新时间
            let updateTime = ' ';

            // 漫画标签
            let tags = [];
            document.querySelectorAll("div.py-1 > a").forEach(tag => {
                tags.push(tag.text.trim());
            });

            // 漫画章节
            // 获取漫画真实id
            let cmoicId = document.querySelector("#mangachapters").attributes["data-mid"];
            // 获取章节json数据 https://api-get-v3.mgsearcher.com/api/manga/get?mid=29730&mode=all

            let chapterListUrl = `https://api-get-v3.mgsearcher.com/api/manga/get?mid=${cmoicId}&mode=all`;
            let chapterRes = await Network.get(chapterListUrl);
            if (chapterRes.status !== 200) {throw `Invalid status code: ${chapterRes.status}`;}
            let chapterData = JSON.parse(chapterRes.body)

            // https://godamh.com/manga/quanminzhuanzhiyulongshishizuiruozhiye/29730-040121960-0
            /**
             * {
                "code": 200,
                "data": {
                    "chapters": [
                        {
                            "attributes": {
                                "isAd": 1,
                                "order": 0,
                                "slug": "29730-040121960-0",
                                "title": "第1话 最弱隐藏职业？！",
                                "updatedAt": "2024-09-11T00:02:43.017Z"
                            },
                            "id": "1449789"
                        },
             */
            // 这里的slug是拼接网址 title是章节名 updatedAt是更新时间

            let chapters = new Map();
            // 遍历 chapters 数组
            if (chapterData.data && chapterData.data.chapters) {
                for (const chapter of chapterData.data.chapters) {
                    const chapterId = chapter.id;
                    const title = chapter.attributes?.title;
                    
                    // 如果 slug 和 title 都不为空，则添加到 Map 中
                    if (chapterId && title) {
                        const epid = `${cmoicId}/${chapterId}`; // 拼接漫画id和章节id
                        chapters.set(epid, title);
                    }
                }
            }


            return {
                title: title,
                cover: cover,
                description: description,
                tags: {
                    "作者": [author],
                    "更新": [updateTime],
                    "标签": tags
                },
                chapters: chapters
            };
        },
        /**
         * 加载章节图片
         * @param comicId {string}
         * @param epId {string?}
         * @returns {Promise<{images: string[]}>}
         */
        loadEp: async (comicId, epId) => {
            /*
            ```
            return {
                // string[]
                images: images
            }
            ```
            */

            // epid经过处理拼接成漫画id和章节id 123/456
            let parts = epId.split('/');
            let m = parts[0];
            let c = parts[1];
            // 获取json文件 https://api-get-v3.mgsearcher.com/api/chapter/getinfo?m=29730&c=1734488
            // m为漫画id，c为章节id
            let chapterListUrl = `https://api-get-v3.mgsearcher.com/api/chapter/getinfo?m=${m}&c=${c}`;
            let chapterRes = await Network.get(chapterListUrl);
            if (chapterRes.status !== 200) {throw `Invalid status code: ${chapterRes.status}`;}
            let chapterData = JSON.parse(chapterRes.body)

            let images = [];
            // 图片地址 https://f40-1-4.g-mh.online替换
            if (chapterData.data && chapterData.data.info.images.images) {
                for (const chapter of chapterData.data.info.images.images) {
                    const imgUrl = chapter?.url;
                    let imagesUrl = `https://f40-1-4.g-mh.online${imgUrl}`;
                    images.push(imagesUrl);
                }
            }
            return{
                images: images
            }

        },
        // {string?} - 正则表达式字符串，用于从用户输入中识别漫画ID
        idMatch: null,
        // 启用标签翻译
        enableTagsTranslate: false,
    }
}
